﻿using System;
using System.IO;
using UnityEditor;
using UnityEngine;

namespace PSDUIImporter
{
    //------------------------------------------------------------------------------
    // class definition
    //------------------------------------------------------------------------------
    public class PSDImportMenu : Editor
    {
        public const string PSDImportDir = "/PSD2UGUI/Samples";

        [MenuItem("QuickTool/PSDImport ...", false, 1)]
        static public void ImportPSD()
        {
            string inputFile = EditorUtility.OpenFilePanel("Choose PSDUI File to Import", PSDImporterConst.PSD_IMPORT_PATH, "xml");

            if (!string.IsNullOrEmpty(inputFile) &&
                inputFile.StartsWith(Application.dataPath))
            {
                GenPSDImportByXml(inputFile);
            }

            GC.Collect();

            Debug.Log("ImportPSD Finish.");
        }

        [MenuItem("QuickTool/PSDImport Auto", false, 1)]
        static public void ImportPSDAuto()
        {
            if (!Directory.Exists(PSDImporterConst.PSD_IMPORT_PATH))
                return;

            DirectoryInfo di = new DirectoryInfo(PSDImporterConst.PSD_IMPORT_PATH);
            FileInfo[] files = di.GetFiles("*.xml", SearchOption.AllDirectories);

            foreach (var fi in files)
            {
                string xml = fi.FullName;
                GenPSDImportByXml(xml);
            }

            GC.Collect();

            Debug.Log($"ImportPSDAuto Finish Length[{files.Length}]");
        }

        static private void GenPSDImportByXml(string xml)
        {
            if (!xml.EndsWith(".xml"))
                return;

            if (!File.Exists(xml))
                return;

            PSDImportCtrl import = new PSDUIImporter.PSDImportCtrl(xml);
            import.BeginDrawUILayers();
            import.BeginSetUIParents();
            import.SaveAsPrefabAsset();

            Debug.Log($"GenPSDImportByXml => {xml}");
        }
    }
}